/* ====================================================================
 * (#)Header: XslTransformer.java
 * (#)Revision: 
 * (#)Date Created: Mar 2, 2007 12:07:22 AM
 * (#)Created By: Karol Wozniak
 * ====================================================================
 *
 * Copyright (c) 2007 karolak .  All rights reserved.
 *
 * ====================================================================
 * 
 * The software application represented here is the sole property of 
 * karolak. Its unauthorized utilization is expressly prohibited.
 * 
 * ====================================================================
 */
package com.karolak.xml;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

/**
 * <code>XslTransformer</code> is used to ....
 * 
 * @author <a href="mailto:kwozniak@hotmail.com">Karol Wozniak</a>
 */
public class XslTransformer {

	static {
		instance = new XslTransformer();
	}

	private static XslTransformer instance;

	private XslTransformer() {
	}

	public String transform(String xsl, String xml) {
		if (isEmpty(xml) || isEmpty(xsl)) {
			return xml;
		}
		Source xsltSource = new StreamSource(new StringReader(xsl));
		Source xmlSource = new StreamSource(new StringReader(xml));
		StreamResult xmlResult = new StreamResult(new StringWriter());
		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer transformer = null;
		try {
			transformer = factory.newTransformer(xsltSource);
			transformer.transform(xmlSource, xmlResult);
		} catch (TransformerConfigurationException e) {
			throw new RuntimeException(e);
		} catch (TransformerException e) {
			throw new RuntimeException(e);
		}
		String result = xmlResult.getWriter().toString();
		return result;
	}

	protected boolean isEmpty(String str) {
		return str == null || str.trim().length() == 0;
	}

	// === get/set === //
	public static XslTransformer getInstance() {
		return instance;
	}
}
